﻿using System;

namespace Microsoft.Popfly.GameCreator.GameEngine.Events
{
    public class VisualSceneLeaveChecker : IEventChecker
    {
        private Actor m_owner;
        private bool m_wasOffScene;
        private bool m_firstRun;

        private DirectionChecker m_directionChecker;

        public VisualSceneLeaveChecker(BehaviorOwner owner, Data.SceneEventInfo eventInfo)
        {
            if (owner.GetType() != typeof(Actor))
            {
                throw new ArgumentException(
                    Utils.ErrorMessagePrefix +
                    "Scene enter events only apply to Actors, but one is being created for a '" +
                    owner.GetType().ToString() +
                    "'."
                    );
            }

            if (eventInfo != null && eventInfo.directions != null)
            {
                m_directionChecker = new DirectionChecker(eventInfo.directions);
            }

            m_owner = (Actor) owner;

            m_firstRun = true;
        }

        #region IEventChecker Members

        public bool FireThisFrame(double elapsedTimeInSeconds, out BehaviorOwner sender, out PGCEventArgs args)
        {
            if (m_firstRun)
            {
                m_firstRun = false;

                m_wasOffScene = m_owner.IsVisualOffScene();

                sender = null;
                args = null;
                return false;
            }
            bool isOffScene = m_owner.IsVisualOffScene();
            if (m_wasOffScene)
            {
                m_wasOffScene = isOffScene;
                sender = null;
                args = null;
                return false;
            }
            else
            {
                if (!isOffScene)
                {
                    sender = null;
                    args = null;
                    return false;
                }
                else
                {
                    m_wasOffScene = true;

                    if (m_directionChecker == null || m_directionChecker.CheckDirection(m_owner.MostRecentVisualSceneOverlapDirection.FilterDirection))
                    {
                        sender = m_owner;
                        args = new EnterLeaveEventArgs(m_owner.MostRecentVisualSceneOverlapDirection);
                        
                        return true;
                    }
                    else
                    {
                        sender = null;
                        args = null;
                        return false;
                    }
                }
            }
        }

        public bool IsOfEventType(string eventType)
        {
            return eventType == "SceneLeave";
        }

        #endregion
    }
}
